
package modele;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import modele.exceptions.AnalyseInexistanteException;

/**
 *
 * @author Danicela
 */
public class Analyse
{

    private int id;
    private String identifiant;
    private String commentaire;

    public Analyse(int id, String identifiant, String commentaire) {
        this.id = id;
        this.identifiant = identifiant;
        this.commentaire = commentaire;
    }

    public int getId()
    {
        return id;
    }

    public String getCommentaire() {
        return commentaire;
    }

    public String getIdentifiant() {
        return identifiant;
    }

    //Accès BD

    public static List<Analyse> getToutesLesAnalyses() throws SQLException
    {
        List<Analyse> resultat = new ArrayList<Analyse>();

        String requete = "Select id_analyse, identifiant, commentaire from analysetable order by identifiant;";
        Connection c = Database.getConnection();
        Statement s = c.createStatement();
        ResultSet rs = s.executeQuery(requete);

        while(rs.next())
        {
            int idAnalyse = rs.getInt(1);
            String identifiant = rs.getString(2);
            String commentaire = rs.getString(3);
            Analyse a = new Analyse(idAnalyse, identifiant, commentaire);

            resultat.add(a);
        }

        c.close();

        return resultat;
    }

    public static Analyse getAnalyse(int idAnalyse) throws AnalyseInexistanteException, SQLException
    {
        Analyse resultat = null;

        String requete = "Select identifiant, commentaire from analysetable where id_analyse = ?;";
        Connection c = Database.getConnection();
        PreparedStatement ps = c.prepareStatement(requete);
        ps.setInt(1, idAnalyse);
        ResultSet rs = ps.executeQuery();

        if(rs.next())
        {
            //L'analyse existe
            String identifiant = rs.getString(1);
            String commentaire = rs.getString(2);
            resultat = new Analyse(idAnalyse, identifiant, commentaire);
        }
        else
        {
            //L'analyse n'existe pas
            throw new AnalyseInexistanteException();
        }

        c.close();

        return resultat;

    }

    public static void enregistrerNouvelleAnalyse(String identifiant, String commentaire) throws SQLException
    {
        String requete = "Insert into analysetable(identifiant, commentaire) values(?, ?);";
        Connection c = Database.getConnection();
        PreparedStatement ps = c.prepareStatement(requete);
        ps.setString(1, identifiant);
        ps.setString(2, commentaire);

        ps.executeUpdate();

        c.close();
    }

}
